package com.jshoperxms.components.netease.im;

import com.jshoperxms.Response;
import com.jshoperxms.components.netease.CheckSumBuilder;
import com.jshoperxms.components.netease.JPNeteaseKey;
import com.jshoperxms.components.netease.bean.ImUserBean;
import com.jshoperxms.components.netease.bean.ImUsersBean;
import com.jshoperxms.components.netease.modal.ImUserCreateVo;
import com.jshoperxms.controller.utils.DateTools;
import com.jshoperxms.controller.utils.PrimaryKey;
import com.jshoperxms.controller.utils.enums.BaseEnums;
import com.jshoperxms.controller.utils.json.GsonJson;
import com.jshoperxms.controller.utils.statickey.TagWords;
import com.jshoperxms.entity.NeteaseimMemberRpT;
import com.jshoperxms.service.NeteaseimMemberRpTService;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.json.JSONArray;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;

/**
 * Created by sdywcd on 2018/4/16.
 * Des:网易IM基础操作防范
 */
@RestController
@RequestMapping("/jp/netease/im")
public class NeteaseIMController {



    //随机数
    private static final String NONCE="00112233445566778899";

    @Resource
    private NeteaseimMemberRpTService neteaseimMemberRpTService;


    /**
     * 创建网易云IM用户id
     * @return
     */
    @RequestMapping(value = "/createNeteaseImUser",method = RequestMethod.POST)
    public ResponseEntity neteaseCreateImId(@RequestBody ImUserCreateVo rq) throws IOException {
        Map<String,Object> data=new HashMap<>();
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost=new HttpPost(IMUrl.createUser);
        String curTime=String.valueOf((new Date()).getTime()/1000L);
        String checkSum= CheckSumBuilder.getCheckSum(JPNeteaseKey.SECRET,NONCE,curTime);
        // 设置请求的header
        httpPost.addHeader("AppKey", JPNeteaseKey.APPKEY);
        httpPost.addHeader("Nonce", NONCE);
        httpPost.addHeader("CurTime", curTime);
        httpPost.addHeader("CheckSum", checkSum);
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        // 设置请求的参数
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("accid", rq.getNeteaseid()));
        nvps.add(new BasicNameValuePair("name",rq.getNeteasename()));
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
        CloseableHttpResponse response=httpclient.execute(httpPost);
        ImUserBean imUserBean= GsonJson.parsejsonToObject(EntityUtils.toString(response.getEntity()),ImUserBean.class);
        data.put("imuserbean",imUserBean);
        NeteaseimMemberRpT neteaseimMemberRpT=new NeteaseimMemberRpT();
        neteaseimMemberRpT.setId(PrimaryKey.get().toString());
        neteaseimMemberRpT.setMemberid(rq.getNeteaseid());
        neteaseimMemberRpT.setCreatetime(DateTools.getSystemTimeLong());
        neteaseimMemberRpT.setUpdatetime(DateTools.getSystemTimeLong());
        neteaseimMemberRpT.setCreatorid("0");
        neteaseimMemberRpT.setStatus(BaseEnums.DataUsingState.USING.getState());
        neteaseimMemberRpT.setImaccid(imUserBean.getInfo().getAccid());
        neteaseimMemberRpT.setImtoken(imUserBean.getInfo().getToken());
        neteaseimMemberRpT.setImname(imUserBean.getInfo().getName());
        this.neteaseimMemberRpTService.save(neteaseimMemberRpT);
        return Response.success(data);
    }


    /**
     * 更新网易IMTOKEN
     * @param rq
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/updateNeteaseImToken",method = RequestMethod.POST)
    public ResponseEntity neteaseUpdateImToken(@RequestBody ImUserCreateVo rq) throws IOException {
        Map<String,Object> data=new HashMap<>();
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost=new HttpPost(IMUrl.updateUserToken);
        String curTime=String.valueOf((new Date()).getTime()/1000L);
        String checkSum= CheckSumBuilder.getCheckSum(JPNeteaseKey.SECRET,NONCE,curTime);
        // 设置请求的header
        httpPost.addHeader("AppKey", JPNeteaseKey.APPKEY);
        httpPost.addHeader("Nonce", NONCE);
        httpPost.addHeader("CurTime", curTime);
        httpPost.addHeader("CheckSum", checkSum);
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        // 设置请求的参数
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("accid", rq.getNeteaseid()));
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
        CloseableHttpResponse response=httpclient.execute(httpPost);
        ImUserBean imUserBean= GsonJson.parsejsonToObject(EntityUtils.toString(response.getEntity()),ImUserBean.class);
        data.put("imuserbean",imUserBean);
        //更新本地数据库中的token
        Criterion criterion= Restrictions.eq("imaccid",imUserBean.getInfo().getAccid());
        NeteaseimMemberRpT neteaseimMemberRpT=this.neteaseimMemberRpTService.findOneByCriteria(NeteaseimMemberRpT.class,criterion);
        if(neteaseimMemberRpT!=null){
            neteaseimMemberRpT.setImtoken(imUserBean.getInfo().getToken());
            neteaseimMemberRpT.setUpdatetime(DateTools.getSystemTimeLong());
            neteaseimMemberRpT.setVersiont(neteaseimMemberRpT.getVersiont()+1);
            this.neteaseimMemberRpTService.update(neteaseimMemberRpT);
            data.put(TagWords.SUCCESS,true);
            data.put("imtoken",neteaseimMemberRpT.getImtoken());
        }
        return Response.success(data);
    }


    /**
     * 封禁Imuser
     * @param rq
     * @return
     */
    @RequestMapping(value = "/blockNeteaseImUser",method = RequestMethod.POST)
    public ResponseEntity neteaseBlockImUser(@RequestBody ImUserCreateVo rq) throws IOException {
        Map<String,Object> data=new HashMap<>();
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost=new HttpPost(IMUrl.blockUser);
        String curTime=String.valueOf((new Date()).getTime()/1000L);
        String checkSum= CheckSumBuilder.getCheckSum(JPNeteaseKey.SECRET,NONCE,curTime);
        // 设置请求的header
        httpPost.addHeader("AppKey", JPNeteaseKey.APPKEY);
        httpPost.addHeader("Nonce", NONCE);
        httpPost.addHeader("CurTime", curTime);
        httpPost.addHeader("CheckSum", checkSum);
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        // 设置请求的参数
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("accid", rq.getNeteaseid()));
        nvps.add(new BasicNameValuePair("needkick","true"));
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
        CloseableHttpResponse response=httpclient.execute(httpPost);
        ImUserBean imUserBean= GsonJson.parsejsonToObject(EntityUtils.toString(response.getEntity()),ImUserBean.class);
        if(imUserBean.getCode()== HttpStatus.SC_OK){
            //更新本地数据库中的token
            Criterion criterion= Restrictions.eq("imaccid",rq.getNeteaseid());
            NeteaseimMemberRpT neteaseimMemberRpT=this.neteaseimMemberRpTService.findOneByCriteria(NeteaseimMemberRpT.class,criterion);
            if(neteaseimMemberRpT!=null){
                neteaseimMemberRpT.setStatus(BaseEnums.DataUsingState.UNUSING.getState());
                neteaseimMemberRpT.setUpdatetime(DateTools.getSystemTimeLong());
                neteaseimMemberRpT.setVersiont(neteaseimMemberRpT.getVersiont()+1);
                this.neteaseimMemberRpTService.update(neteaseimMemberRpT);
                data.put(TagWords.SUCCESS,true);
            }
        }else{
            data.put(TagWords.SUCCESS,false);
        }
        return Response.success(data);
    }

    /**
     * 解禁网易云IMid
     * @param rq
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/unBlockNeteaseImUser",method = RequestMethod.POST)
    public ResponseEntity neteaseUnBlockImUser(@RequestBody ImUserCreateVo rq) throws IOException {
        Map<String,Object> data=new HashMap<>();
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost=new HttpPost(IMUrl.unblockUser);
        String curTime=String.valueOf((new Date()).getTime()/1000L);
        String checkSum= CheckSumBuilder.getCheckSum(JPNeteaseKey.SECRET,NONCE,curTime);
        // 设置请求的header
        httpPost.addHeader("AppKey", JPNeteaseKey.APPKEY);
        httpPost.addHeader("Nonce", NONCE);
        httpPost.addHeader("CurTime", curTime);
        httpPost.addHeader("CheckSum", checkSum);
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        // 设置请求的参数
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("accid", rq.getNeteaseid()));
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
        CloseableHttpResponse response=httpclient.execute(httpPost);
        ImUserBean imUserBean= GsonJson.parsejsonToObject(EntityUtils.toString(response.getEntity()),ImUserBean.class);
        if(imUserBean.getCode()== HttpStatus.SC_OK){
            //更新本地数据库中的token
            Criterion criterion= Restrictions.eq("imaccid",rq.getNeteaseid());
            NeteaseimMemberRpT neteaseimMemberRpT=this.neteaseimMemberRpTService.findOneByCriteria(NeteaseimMemberRpT.class,criterion);
            if(neteaseimMemberRpT!=null){
                neteaseimMemberRpT.setStatus(BaseEnums.DataUsingState.USING.getState());
                neteaseimMemberRpT.setUpdatetime(DateTools.getSystemTimeLong());
                neteaseimMemberRpT.setVersiont(neteaseimMemberRpT.getVersiont()+1);
                this.neteaseimMemberRpTService.update(neteaseimMemberRpT);
                data.put(TagWords.SUCCESS,true);
            }
        }else{
            data.put(TagWords.SUCCESS,false);
        }
        return Response.success(data);
    }


    /**
     * 更新网易云IM信息
     * @param rq
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/updateNeteaseImUserInfo",method = RequestMethod.POST)
    public ResponseEntity neteaseUpdateImUser(@RequestBody ImUserCreateVo rq) throws IOException {
        Map<String,Object> data=new HashMap<>();
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost=new HttpPost(IMUrl.updateUserInfo);
        String curTime=String.valueOf((new Date()).getTime()/1000L);
        String checkSum= CheckSumBuilder.getCheckSum(JPNeteaseKey.SECRET,NONCE,curTime);
        // 设置请求的header
        httpPost.addHeader("AppKey", JPNeteaseKey.APPKEY);
        httpPost.addHeader("Nonce", NONCE);
        httpPost.addHeader("CurTime", curTime);
        httpPost.addHeader("CheckSum", checkSum);
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        // 设置请求的参数
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("accid", rq.getNeteaseid()));
        nvps.add(new BasicNameValuePair("name", rq.getNeteasename()));
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
        CloseableHttpResponse response=httpclient.execute(httpPost);
        ImUserBean imUserBean= GsonJson.parsejsonToObject(EntityUtils.toString(response.getEntity()),ImUserBean.class);
        if(imUserBean.getCode()== HttpStatus.SC_OK){
            //更新本地数据库中的token
            Criterion criterion= Restrictions.eq("imaccid",rq.getNeteaseid());
            NeteaseimMemberRpT neteaseimMemberRpT=this.neteaseimMemberRpTService.findOneByCriteria(NeteaseimMemberRpT.class,criterion);
            if(neteaseimMemberRpT!=null){
                neteaseimMemberRpT.setImname(rq.getNeteasename());
                neteaseimMemberRpT.setUpdatetime(DateTools.getSystemTimeLong());
                neteaseimMemberRpT.setVersiont(neteaseimMemberRpT.getVersiont()+1);
                this.neteaseimMemberRpTService.update(neteaseimMemberRpT);
                data.put(TagWords.SUCCESS,true);
            }
        }else{
            data.put(TagWords.SUCCESS,false);
        }
        return Response.success(data);
    }

    /**
     * 获取网易云IM信息
     * @param rq
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/getNeteaseImUserInfo",method = RequestMethod.POST)
    public ResponseEntity neteaseGetImUser(@RequestBody ImUserCreateVo rq) throws IOException {
        Map<String,Object> data=new HashMap<>();
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost=new HttpPost(IMUrl.getUinfos);
        String curTime=String.valueOf((new Date()).getTime()/1000L);
        String checkSum= CheckSumBuilder.getCheckSum(JPNeteaseKey.SECRET,NONCE,curTime);
        // 设置请求的header
        httpPost.addHeader("AppKey", JPNeteaseKey.APPKEY);
        httpPost.addHeader("Nonce", NONCE);
        httpPost.addHeader("CurTime", curTime);
        httpPost.addHeader("CheckSum", checkSum);
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        // 设置请求的参数
        JSONArray jsonArray=new JSONArray();
        jsonArray.put(rq.getNeteaseid());
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("accids",jsonArray.toString()));
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
        CloseableHttpResponse response=httpclient.execute(httpPost);
        ImUsersBean imUserBean= GsonJson.parsejsonToObject(EntityUtils.toString(response.getEntity()),ImUsersBean.class);
        data.put("imuserbean",imUserBean);
        return Response.success(data);
    }




    /**
     * 通过网易云IM创建并返回网易IM用户信息
     * @param neteaseid
     * @param neteasename
     * @return
     * @throws IOException
     */
    public ImUserBean createImId(String neteaseid,String neteasename) throws IOException {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost=new HttpPost(IMUrl.createUser);
        String curTime=String.valueOf((new Date()).getTime()/1000L);
        String checkSum= CheckSumBuilder.getCheckSum(JPNeteaseKey.SECRET,NONCE,curTime);
        // 设置请求的header
        httpPost.addHeader("AppKey", JPNeteaseKey.APPKEY);
        httpPost.addHeader("Nonce", NONCE);
        httpPost.addHeader("CurTime", curTime);
        httpPost.addHeader("CheckSum", checkSum);
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        // 设置请求的参数
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("accid",neteaseid));
        nvps.add(new BasicNameValuePair("name",neteasename));
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
        CloseableHttpResponse response=httpclient.execute(httpPost);
        ImUserBean imUserBean= GsonJson.parsejsonToObject(EntityUtils.toString(response.getEntity()),ImUserBean.class);
        return imUserBean;
    }


    /**
     * 推送消息
     * @throws IOException
     */
    @RequestMapping(value = "/sendMsgtoOne",method = RequestMethod.POST)
    public void sendMsgToOneMember() throws IOException {
        String accid="jppushadmin-1";
        String to="5ae13bf7556f719afdc4643c";//老师id
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost=new HttpPost(IMUrl.sendMsg);
        String curTime=String.valueOf((new Date()).getTime()/1000L);
        String checkSum= CheckSumBuilder.getCheckSum(JPNeteaseKey.SECRET,NONCE,curTime);
        // 设置请求的header
        httpPost.addHeader("AppKey", JPNeteaseKey.APPKEY);
        httpPost.addHeader("Nonce", NONCE);
        httpPost.addHeader("CurTime", curTime);
        httpPost.addHeader("CheckSum", checkSum);
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
       // 设置请求的参数
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("from", accid));
        nvps.add(new BasicNameValuePair("ope", "0"));
        nvps.add(new BasicNameValuePair("to", to));
        nvps.add(new BasicNameValuePair("type", "0"));
        nvps.add(new BasicNameValuePair("body", "{\"msg\":\"hello\"}"));
        nvps.add(new BasicNameValuePair("option","{\"push\":true,\"roam\":true,\"history\":false,\"sendersync\":true,\"route\":false,\"badge\":true,\"needPushNick\":true}"));
        nvps.add(new BasicNameValuePair("pushcontent","nihao"));
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
        // 执行请求
        HttpResponse response = httpclient.execute(httpPost);
        // 打印执行结果
        System.out.println(EntityUtils.toString(response.getEntity(), "utf-8"));}











}
